﻿/*
 * Cratos Desktop
 * Cratos Helper class
 * 
 * Copyright (c) 2011 Draco
 * 
 * This file is part of Cratos.
 * 
 * Cratos is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Cratos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cratos.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *       .==.        .==.
 *      //'^\\      //^'\\
 *     // ^ ^\(\__/)/^ ^^\\
 *    //^ ^^ ^/6  6\ ^^ ^ \\
 *   //^ ^^ ^/( .. )\^ ^ ^ \\
 *  // ^^ ^/\| V""V|/\^ ^ ^ \\
 * //^^/\/ /  '~~'  \ \/\^ ^ \\
 *  ------------------------------------
 *  HERE BE DRAGONS
 *  
 *  Johan Dercksen - johan@draco.co.za
 */
using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Reflection;
using System.Diagnostics;

using Cratos.Tools.General;

namespace Cratos.Desktop
{
	/// <summary>
	/// Server State event handler
	/// </summary>
	public delegate void ServerStateEventHandler();

	/// <summary>
	/// Cratos Helper Class
	/// </summary>
	public static class CratosHelper
	{
		#region Class Constant declarations
		#endregion

		#region Class Event declarations
		#endregion

		#region Class Variable declarations
		private static string m_LogFilename = "Cratos.log";
		#endregion

		#region Class Constructors & Destructors
		#endregion

		#region Class Properties
		/// <summary>
		/// Assembly Version
		/// </summary>
		public static string AssemblyVersion
		{
			get
			{
				return (Assembly.GetEntryAssembly().GetName().Version.Major.ToString() + "." +
								Assembly.GetEntryAssembly().GetName().Version.Minor.ToString().PadLeft(2, '0') + "." +
								Assembly.GetEntryAssembly().GetName().Version.Build.ToString().PadLeft(3, '0'));
			}
		}

		/// <summary>
		/// Log Filename
		/// </summary>
		public static string LogFilename
		{
			get { return (m_LogFilename); }
			set { m_LogFilename = value; }
		}
		#endregion

		#region Class Methods
		/// <summary>
		/// Log a Message
		/// </summary>
		/// <param name="msgSeverity">Message Severity indicator</param>
		/// <param name="msgSource">Message Source</param>
		/// <param name="newMessage">Message</param>
		/// <param name="runtimeException">Runtime Exception</param>
		/// <param name="showMessage">Display Message indicator</param>
		public static void LogMessage(CratosLogSeverity msgSeverity, string msgSource, 
																	string newMessage, Exception runtimeException, bool showMessage)
		{
			// Declare the required variables
			StringBuilder errorMessage = new StringBuilder();
			Exception innerException;

			// Create and setup the new message
			errorMessage = new StringBuilder();
			errorMessage.Append(string.Format("[{0}] {1} : {2}", msgSeverity.ToString(), msgSource, newMessage));

			// Handle the exception if specified
			if (runtimeException != null)
			{
				// Build the error message
				errorMessage.Append("Exception  : " + runtimeException.Message + "\n" +
														"Stack Trace: " + runtimeException.StackTrace + "\n");

				// Retrieve the inner exception
				innerException = runtimeException.InnerException;

				// Handle all the inner exceptions
				while (innerException != null)
				{
					// Append the inner exception message
					errorMessage.AppendLine(innerException.Message);

					// Retrieve the next inner exception
					innerException = innerException.InnerException;
				}
			}

			// Log the message to file if required
			CratosHelper.WriteToLogfile(errorMessage.ToString());

			// Display the message to the user if required
			if (showMessage) { MessageBox.Show(errorMessage.ToString(), "Cratos", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK); }

			// Return to calling method
			return;
		}

		/// <summary>
		/// Write the message to the Application log file
		/// </summary>
		/// <param name="newMessage">Message to be appended</param>
		/// <returns>
		/// A boolean value indicating the success of the method
		/// </returns>
		public static bool WriteToLogfile(string newMessage)
		{
			// Declare the required variables
			string				baseDir;
			StreamWriter	logFile = null;

			try
			{
				// Determine the Base Directory
				baseDir = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\";

				// Create and open the relevant log file
				if (File.Exists(baseDir + CratosHelper.LogFilename)) { logFile = File.AppendText(baseDir + CratosHelper.LogFilename); }
				else { logFile = File.CreateText(baseDir + CratosHelper.LogFilename); }

				// Write the request block to file
				logFile.WriteLine(string.Format("[ {0} ] {1}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), newMessage));

				// Flush and close the log file
				logFile.Flush();
				logFile.Close();
			}
			catch (Exception) { }
			finally
			{
				// Close the file
				if (logFile != null) { logFile.Close(); }
			}

			// Return to calling method
			return (true);
		}
		#endregion

		#region Class Support Methods
		#endregion
	}
}
